using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using Dapper;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Linq;
namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    public class GetExportInfoCommandHandler : IRequestHandler<GetExportInfoCommands, APIResult<byte[]>>
    {
        private readonly IBaseRepository<Customer> _customerRep;

        public GetExportInfoCommandHandler(IBaseRepository<Customer> customerRep)
        {
            _customerRep = customerRep;
        }

        public async Task<APIResult<byte[]>> Handle(GetExportInfoCommands request, CancellationToken cancellationToken)
        {
            try
            {
                var where = "IsDeleted = false";
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    where += " AND CustomerName LIKE @CustomerName";
                    param.Add("@CustomerName", $"%{request.CustomerName}%");
                }
                if (!string.IsNullOrWhiteSpace(request.Phone))
                {
                    where += " AND Phone LIKE @Phone";
                    param.Add("@Phone", $"%{request.Phone}%");
                }

                var data = _customerRep.GetAll(where, param);
                var list = data?.ToList() ?? new List<Customer>();
                if (list.Count == 0)
                {
                    return new APIResult<byte[]>
                    {
                        Code = APIEnums.Fail,
                        Msg = "没有可导出的客户数据",
                        Data = Array.Empty<byte>()
                    };
                }

                var wb = new XSSFWorkbook();
                var sheet = wb.CreateSheet("客户列表");

                var headers = new[]
                {
                    "客户名称","客户别名","简称","省","市","地址","邮编","电话","信用等级","信用额度","客户分类","备注","状态","创建时间","创建人"
                };

                var headerRow = sheet.CreateRow(0);
                for (int i = 0; i < headers.Length; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(headers[i]);
                }

                for (int r = 0; r < list.Count; r++)
                {
                    var c = list[r];
                    var row = sheet.CreateRow(r + 1);

                    row.CreateCell(0).SetCellValue(c.CustomerName ?? string.Empty);
                    row.CreateCell(1).SetCellValue(c.CustomerAlias ?? string.Empty);
                    row.CreateCell(2).SetCellValue(c.ShortName ?? string.Empty);
                    row.CreateCell(3).SetCellValue(c.Province ?? string.Empty);
                    row.CreateCell(4).SetCellValue(c.City ?? string.Empty);
                    row.CreateCell(5).SetCellValue(c.Address ?? string.Empty);
                    row.CreateCell(6).SetCellValue(c.ZipCode ?? string.Empty);
                    row.CreateCell(7).SetCellValue(c.Phone ?? string.Empty);
                    row.CreateCell(8).SetCellValue(c.CreditLevel ?? string.Empty);
                    row.CreateCell(9).SetCellValue(c.CreditLimit?.ToString() ?? string.Empty);
                    row.CreateCell(10).SetCellValue(c.CustomerType ?? string.Empty);
                    row.CreateCell(11).SetCellValue(c.Remark ?? string.Empty);
                    row.CreateCell(12).SetCellValue(c.Status ? "正常" : "停用");
                    row.CreateCell(13).SetCellValue(c.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(14).SetCellValue(c.CreateUser ?? string.Empty);
                }

                using var ms = new MemoryStream();
                wb.Write(ms);
                ms.Flush();
                var bytes = ms.ToArray();

                if (bytes.Length == 0)
                {
                    return new APIResult<byte[]>
                    {
                        Code = APIEnums.Fail,
                        Msg = "生成的Excel文件为空",
                        Data = Array.Empty<byte>()
                    };
                }

                return new APIResult<byte[]>
                {
                    Code = APIEnums.Success,
                    Msg = $"成功导出{list.Count}条数据",
                    Data = bytes
                };
            }
            catch (Exception ex)
            {
                return new APIResult<byte[]>
                {
                    Code = APIEnums.Fail,
                    Msg = "导出失败：" + ex.ToString(),
                    Data = Array.Empty<byte>()
                };
            }
        }
    }
}
